﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Web;
using Klinkby.Properties;

namespace Klinkby
{
    static class ResponseCompression
    {
        readonly static KeyValuePair<DecompressionMethods, Func<Stream, Stream>>[] compressionMethods =
            new[] {
            new KeyValuePair<DecompressionMethods, Func<Stream, Stream>>(
                DecompressionMethods.GZip, 
                inStream => new GZipStream(inStream, CompressionMode.Compress)
                ),
            new KeyValuePair<DecompressionMethods, Func<Stream, Stream>>(
                DecompressionMethods.Deflate, 
                inStream => new DeflateStream(inStream, CompressionMode.Compress)
                ),
        };

        public static void Support(HttpContext context)
        {
            var request = context.Request;
            var method = compressionMethods.FirstOrDefault(
                m =>
                {
                    string wish;
                    return ((wish = request.Headers[Resources.AcceptEncoding]) != null)
                        ? wish.ContainsIgnoreCase(m.Key.ToString())
                        : false;
                });
            if (method.Key != DecompressionMethods.None)
            {
                var response = context.Response;
                response.AppendHeader(Resources.ContentEncoding, method.Key.ToString().ToLowerInvariant());
                response.Filter = method.Value(response.Filter);
            }
        }
    }
}